import React, { useEffect, useState } from 'react'
import { Menu,Layout } from 'antd'
import { MailOutlined,AppstoreOutlined,SettingOutlined } from '@ant-design/icons'
import './sider.scss'
import { useNavigate, useLocation } from 'react-router-dom'

const { Sider } = Layout;


const items = [
  {
    key: 'sub1',
    label: '首页',
    icon: <MailOutlined />,
    children: [
      {
        key: 'g1',
        label: '用户管理',
        type: 'group',
        children: [
          { key: 'user_add', label: '添加用户' },
          { key: 'user_delete', label: '删除用户' },
        ],
      },
      {
        key: 'g2',
        label: '权限管理',
        type: 'group',
        children: [
          { key: 'role_list', label: '角色列表' },
          { key: 'permission_list', label: '权限列表' },
        ],
      },
    ],
  },
  {
    key: 'sub2',
    label: '新闻管理',
    icon: <AppstoreOutlined />,
    children: [
      { key: 'news_list', label: '新闻列表' },
      { key: 'news_category', label: '新闻分类' },
    ],
  },
  {
    key: 'sub4',
    label: '文章管理',
    icon: <SettingOutlined />,
    children: [
      { key: 'article_list', label: '文章列表' },
      { key: 'article_category', label: '文章分类' },
      { key: 'tag_manage', label: '标签管理' },
      { key: 'comment_manage', label: '评论管理' },
    ],
  }
];

export default function SideMenu() {
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedKeys, setSelectedKeys] = useState(['user_add']);
  
  // 根据当前路径获取当前选中的菜单项
  useEffect(() => {
    const path = location.pathname;
    const pathParts = path.split('/');
    if (pathParts.length > 2) {
      const key = pathParts[pathParts.length - 1];
      setSelectedKeys([key]);
    }
  }, [location]);
  
  // 处理菜单点击事件
  const handleMenuClick = (e) => {
    navigate(`/news/${e.key}`);
  };

  return (
      <Sider trigger={null} collapsible collapsed={false}>
        <div className="demo-logo-vertical">
          新闻发布系统
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={selectedKeys}
          items={items}
          onClick={handleMenuClick}
        />
      </Sider>
  )
}
